/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ucm;

import java.sql.ResultSet;
import sql.INSERT_SQL;
import sql.SELECT_SQL;
import sql.UPDATE_SQL;
import view.DomeMain_View;

/**
 *
 * @author 马凯
 */
public class CheckDomeView_UC {

    private static CheckDomeView_UC cdv;
    private DomeMain_View dmv;
    private String apartment;
    private String room;
    private String date = null;
    private String cid;
    private String psw;

    public static CheckDomeView_UC getInstance(DomeMain_View dmv) {
        if (cdv == null) {
            cdv = new CheckDomeView_UC();
            cdv.dmv = dmv;
            cdv.apartment = dmv.getViewModel().getBuilding_CB().getSelectedItem().toString();
            cdv.room = dmv.getViewModel().getDomeNo_TF().getText();
        } else {
            cdv.dmv = dmv;
            cdv.apartment = dmv.getViewModel().getBuilding_CB().getSelectedItem().toString();
            cdv.room = dmv.getViewModel().getDomeNo_TF().getText();
        }
        return cdv;
    }

    public void run() {
        cid = dmv.getViewModel().getCid_TF().getText();
        psw = dmv.getViewModel().getPsw_TF().getText();
        if (dmv.getViewModel().getCid_TF().getText().length() != 10) {
            System.out.println("You should input the card id in chart.");
            dmv.getViewModel().getNote_La().setText("You should input the card id in chart.");
        } else if (dmv.getViewModel().getCid_TF().getText().length() <= 0 && dmv.getViewModel().getPsw_TF().getText().length() >= 15) {
            dmv.getViewModel().getNote_La().setText("You should input the card id in true formate.");
        } else {
            String query = "SELECT roll_id FROM rfid WHERE cid='" + cid + "' and password = '" + psw + "';";
            System.out.println(query);
            ResultSet rs = SELECT_SQL.getInstance().run(query);
            try {
                if (rs.wasNull()) {
                    dmv.getViewModel().getNote_La().setText("The card id or psw is fault.");
                } else {
                    rs.first();
                    String roll_id = rs.getString("roll_id").toString();
                    query = "INSERT INTO dormitory(apartment,room,rid,start_date,end_date) VALUES ('" + apartment + "','" + room +
                            "','" + roll_id + "','" + "2007-05-05" + "','" + "2007-05-05" + "')";
                    System.out.println(query);
                    INSERT_SQL.getInstance().run(query);
                    dmv.getViewModel().getNote_La().setText("The query is insert successfully.");
                    query = "UPDATE roll SET dormitory = '" + apartment + "-" + room + "' WHERE card_id='"+cid+"';";
                    System.out.println(query);
                    UPDATE_SQL.getInstance().run(query);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
